// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// u [author] rhyme_lph
// K [email]  rhymelph@gmail.com
// S [github] https://github.com/rhymelph

import 'dart:io';

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/a.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/provider/login/login_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:finance_app/src/widgets/button/normal_button.dart';
import 'package:finance_app/src/widgets/common/normal_error_text.dart';
import 'package:finance_app/src/widgets/input/input_field.dart';
import 'package:finance_app/src/widgets/input/phone_number_input_field.dart';
import 'package:finance_app/src/widgets/login/login_top_screen_widget.dart';
import 'package:finance_app/src/widgets/select/normal_radio.dart';
import 'package:finance_app/src/widgets/wrapper/normal_form_wrapper.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_svg/svg.dart';
import 'package:tuple/tuple.dart';

@RouterMeta(paramName: "loginPage")
class LoginPage extends StatefulWidget {
  final String toastMessage;

  const LoginPage({Key key, this.toastMessage}) : super(key: key);

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage>
    with PagePresenter<LoginPage, LoginProvider> {
  @override
  void initState() {
    super.initState();

    SchedulerBinding.instance.addPostFrameCallback((timeStamp) {
      if (Config.showLogin) {
        RProvider.myProvider.globalMap[ConfigKey.showLogin] = false;
        if ((Platform.isAndroid &&
                Config.settingApp.androidRegisterStatus == 1) ||
            (Platform.isIOS && Config.settingApp.iosRegisterStatus == 1)) {
          provider.onNavRegister();
        }
      }
      if (widget.toastMessage != null) {
        BaseConfig.dialogBase
            .showToast(context: context, content: widget.toastMessage);
      }
    });
  }

  @override
  Widget get buildWidget => Scaffold(
        body: ColoredBox(
          color: Colors.white,
          child: ListView(
            padding: EdgeInsets.zero,
            children: [
              _buildImageScreen(),
              AppSpaces.h35,
              NormalFormWrapper(
                topPadding: getDp(22),
                bottomPadding: getDp(24),
                leftPadding: getDp(50),
                child: listBuilder<String>(
                  selector: (_, __) => __.currentType,
                  builder: (BuildContext context, String value, Widget child) =>
                      Row(
                    children: [S.current.email, S.current.mobile_number]
                        .map(
                          (e) => PressedOpacityButton(
                            onPressed: () {
                              provider.onChangeType(e);
                            },
                            child: NormalRadio(
                              title: e,
                              isSelect: value == e,
                            ),
                          ),
                        )
                        .toList(),
                  ),
                ),
              ),
              listBuilder<bool>(
                selector: (_, __) => __.currentType == S.current.email,
                builder: (BuildContext context, bool value, Widget child) =>
                    value
                        ? listBuilder<bool>(
                            selector: (_, __) => false,
                            builder: (BuildContext context, bool value,
                                    Widget child) =>
                                InputField(
                              // leading: Icon(
                              //   Icons.email,
                              //   size: 15,
                              // ),
                              hint: S.current.email,
                              hasError: value,
                              focusNode: provider.emailFocusNode,
                              controller: provider.emailController,
                            ),
                          )
                        : listBuilder<String>(
                            selector: (_, __) => __.countryCode,
                            builder: (BuildContext context, String value,
                                    Widget child) =>
                                PhoneNumberInputField(
                              defaultCountryCode: value,
                              focusNode: provider.phoneFocusNode,
                              controller: provider.phoneController,
                              countryCodeCallback: provider.onChangeCountryCode,
                            ),
                          ),
              ),
              AppSpaces.h30,
              listBuilder<bool>(
                  builder: (BuildContext context, bool value, Widget child) =>
                      InputField(
                        key: ValueKey('password'),
                        leading: SvgPicture.asset(
                          A.assetsImagesCreatePadlock2,
                          width: getDp(15),
                          height: getDp(15),
                        ),
                        tip: S.current.password,
                        isPassword: true,
                        hasError: value,
                        controller: provider.passwordController,
                        focusNode: provider.passwordFocusNode,
                      ),
                  selector: (_, __) => __.passwordError),
              listBuilder<Tuple2<bool, bool>>(
                selector: (_, __) => Tuple2<bool, bool>(
                    __.loginFailed != null, __.currentType == S.current.email),
                builder: (BuildContext context, Tuple2<bool, bool> value,
                        Widget child) =>
                    NormalErrorText(
                  margin: EdgeInsets.only(left: getDp(45), top: getDp(20)),
                  content: value.item2
                      ? 'Email or password is incorrect'
                      : S.current.mobile_number_incorrect,
                  isVisibility: value.item1,
                ),
              ),
              AppSpaces.h25,
              listBuilder<bool>(
                  builder: (BuildContext context, bool value, Widget child) =>
                      value == true
                          ? Padding(
                              padding: EdgeInsets.only(bottom: getDp(25)),
                              child: PressedOpacityButton(
                                onPressed: provider.onFingerLogin,
                                child: SvgPicture.asset(
                                  A.assetsImagesLoginFingerprintSmall,
                                  width: getDp(30),
                                  height: getDp(30),
                                  color: aceBlueColor,
                                  fit: BoxFit.contain,
                                ),
                              ),
                            )
                          : Container(),
                  selector: (_, __) =>
                      __.enableAuth && Config.biometricsEnable == true),
              listBuilder<bool>(
                  builder: (BuildContext context, bool value, Widget child) =>
                      NormalButton(
                        title: S.current.login,
                        onTap: value == true ? provider.onLogin : null,
                      ),
                  selector: (_, __) => __.enable),
              AppSpaces.h30,
              Center(
                  child: PressedOpacityButton(
                onPressed: provider.onNavForgotPassword,
                child: Text(
                  S.current.forgot_password_question,
                  style: TextStyle(
                    color: aceDarkGrayColor,
                    fontSize: getSp(14),
                    fontWeight: FontWeight.w400,
                    height: 16 / 14,
                  ),
                ),
              )),
              AppSpaces.h26,
              Visibility(
                visible: (Platform.isAndroid &&
                        Config.settingApp?.androidRegisterStatus == 1) ||
                    (Platform.isIOS &&
                        Config.settingApp?.iosRegisterStatus == 1),
                child: Column(
                  children: [
                    _buildOrDivider(),
                    AppSpaces.h26,
                    Center(
                      child: Text.rich(TextSpan(
                          text: S.current.not_have_account,
                          children: [
                            TextSpan(
                                text: S.current.register_here,
                                style: TextStyle(
                                  color: aceBlueColor,
                                  fontWeight: FontWeight.bold,
                                ),
                                recognizer: TapGestureRecognizer()
                                  ..onTap = provider.onNavRegister)
                          ],
                          style: TextStyle(
                              fontSize: getSp(14),
                              color: aceDarkGrayColor,
                              fontWeight: FontWeight.w400,
                              fontFamily: "DinRoundPro"))),
                    ),
                  ],
                ),
                //   replacement: listBuilder<bool>(
                //     selector: (_, __) => __.isShowIOSRegister,
                //     builder: (BuildContext context, bool value, Widget child) =>
                //         value
                //             ? Column(
                //                 children: [
                //                   _buildOrDivider(),
                //                   AppSpaces.h26,
                //                   Center(
                //                     child: Text.rich(TextSpan(
                //                         children: [
                //                           TextSpan(
                //                               text:
                //                                   S.current.request_for_free_demo,
                //                               style: TextStyle(
                //                                 color: aceBlueColor,
                //                                 fontWeight: FontWeight.bold,
                //                               ),
                //                               recognizer: TapGestureRecognizer()
                //                                 ..onTap = provider.onNavFreeDemo)
                //                         ],
                //                         style: TextStyle(
                //                             fontSize: getSp(14),
                //                             color: aceDarkGrayColor,
                //                             fontWeight: FontWeight.w400,
                //                             fontFamily: "DinRoundPro"))),
                //                   ),
                //                 ],
                //               )
                //             : Container(),
                //   ),
              ),
              AppSpaces.h26,
            ],
          ),
        ),
      );

  Widget _buildImageScreen() => LoginTopScreenWidget(
        imagePath: A.assetsImagesGraphicWelcome,
        imageName: S.current.welcome,
        imageBottom: 10,
      );

  Widget _buildOrDivider() => Container(
        margin: EdgeInsets.symmetric(
          horizontal: getDp(43),
        ),
        child: Row(
          children: [
            Expanded(
                child: Container(
              height: getDp(1),
              color: aceGrayColor,
            )),
            Padding(
              padding: EdgeInsets.symmetric(horizontal: getDp(14)),
              child: Text(
                S.current.or,
                style: TextStyle(
                  color: aceGrayColor,
                  fontSize: getSp(14),
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            Expanded(
                child: Container(
              height: getDp(1),
              color: aceGrayColor,
            )),
          ],
        ),
      );
}
